package com.yan.utils;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.jfinal.kit.StrKit;
import jodd.util.StringUtil;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * @ClassName: HttpUtil
 * @Description: HTTP CLIENT类用于发送HTTP请求
 */
public class HttpUtil {

	private static final Logger logger = Logger.getLogger(HttpUtil.class);

	/**
	 * 连接超时 （单位：秒）
	 */
	private static final int CONNECTION_TIME_OUT = 30;

	/**
	 * 读取数据超时 （单位：秒）
	 */
	private static final int READ_TIME_OUT = 60;

	private HttpUtil() {

	}

	public static URLConnection setHttpProxy(String url, String ip, int port) throws IOException {
		URL u = new URL(url);
		InetSocketAddress addr = new InetSocketAddress(ip, port);
		Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
		return u.openConnection(proxy);
	}

	/*
	  * 
	  */
	public static String getConnectionResult(String strURL, Map<String, String> params, String method, String charSet) {
		String line = "";
		HttpURLConnection httpConn = null;
		InputStreamReader input = null;
		BufferedReader bufReader = null;
		try {
			strURL += getUrlParam(params, charSet);
			logger.info(strURL);
			URL url = new URL(strURL);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setConnectTimeout(1000 * CONNECTION_TIME_OUT);// 设置连接主机超时（单位：毫秒）
			httpConn.setReadTimeout(1000 * READ_TIME_OUT);// 设置从主机读取数据超时（单位：毫秒）
			httpConn.setRequestProperty("Accept-Encoding", "");//设置为空的时候,返回的数据也不会乱码
			httpConn.setRequestMethod(method);
			input = new InputStreamReader(httpConn.getInputStream(), charSet);
			bufReader = new BufferedReader(input);

			StringBuilder contentBuf = new StringBuilder();
			while ((line = bufReader.readLine()) != null) {
				contentBuf.append(line);
			}
			String result = contentBuf.toString();
			return result;
		} catch (Exception e) {
			logger.error("【异常】从远程获取数据", e);
			return "";
		} finally {
			try {
				if (bufReader != null) {
					bufReader.close();
					bufReader = null;
				}
				if (input != null) {
					input.close();
					input = null;
				}
				if (httpConn != null) {
					httpConn.disconnect();// 断开连接
					httpConn = null;
				}
			} catch (Exception e2) {
				logger.error(e2);
			}
		}
	}

	/*
	 * Accept-Encoding 直接使用GZIPInputStream,否则中文乱码
	 */

	public static String getZipConnectionResult(String strURL, Map<String, String> params, String method,
			String charSet) {
		String line;
		HttpURLConnection httpConn = null;
		InputStreamReader input = null;
		BufferedReader bufReader = null;
		GZIPInputStream gzipInputStream = null;
		try {
			strURL += getUrlParam(params, charSet);
			URL url = new URL(strURL);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setConnectTimeout(1000 * CONNECTION_TIME_OUT);// 设置连接主机超时（单位：毫秒）
			httpConn.setReadTimeout(1000 * READ_TIME_OUT);// 设置从主机读取数据超时（单位：毫秒）
			httpConn.setRequestProperty("Accept-Encoding", "gzip");
			gzipInputStream = new GZIPInputStream(httpConn.getInputStream());
			input = new InputStreamReader(gzipInputStream, "UTF-8");
			bufReader = new BufferedReader(input);
			StringBuffer buffer = new StringBuffer();

			while ((line = bufReader.readLine()) != null) {
				buffer.append(line + "\n");
			}

			return buffer.toString();
		} catch (Exception e) {
			logger.error("【异常】从远程获取数据", e);
			return "";
		} finally {
			try {
				if (bufReader != null) {
					bufReader.close();
					bufReader = null;
				}
				if (gzipInputStream != null) {
					gzipInputStream.close();
					gzipInputStream = null;
				}

				if (input != null) {
					input.close();
					input = null;
				}
				if (httpConn != null) {
					httpConn.disconnect();// 断开连接
					httpConn = null;
				}
			} catch (Exception e2) {
				logger.error(e2);
			}
		}
	}

	public static String getUrlParam(Map<String, String> params, String charSet) {
		StringBuffer url = new StringBuffer();
		// 组装参数
		if (params != null && !params.isEmpty()) {
			url.append("?");
			for (String key : params.keySet()) {
				try {
					if (!StrKit.isBlank(params.get(key))) {
						url.append(key + "=" + URLEncoder.encode(params.get(key).toString(), charSet) + "&");
					} else {
						url.append(key + "=&");
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			url.deleteCharAt(url.length() - 1);
		}
		return url.toString();
	}

	public static void main(String[] args) throws IOException {
		// String url =
		// "http://192.168.70.213:8080/chatServer/chat/sendPChatMessage/android/football";
		// String url =
		// "http://192.168.70.213:8080/chatServer/chat/sendPChatMessage/android/football?lang=zh&timeZone=8&message=&chatType=football&toUserId=null&sourceName=android&msgCode=1&msgId=e10ea908-dae9-4824-9ebf-5262f04d577b&thirdId=3482618&deviceId=357095063448756&userId=hhly90320&phoneNum=13570185327&userLogo=http://tp.13322.com/img/2017-06-06/9212f265-8f28-40e3-9032-a2cb412e633c.jpg&userNick=诸葛看盘";
		String url = "http://localhost:10088/JFinal/indexJson";

		String result = HttpUtil.getConnectionResult(url, null, "POST", "utf-8");
		try {

			System.out.println(result);

			// System.out.println(StringsUtil.unGZips(result));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
